<template>
  <div class="home-container">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-box">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索代码片段标题..."
          size="large"
          enter-button="搜索"
          @search="handleSearch"
          @keyup="handleSearch"
          class="search-input"
        />
      </div>
    </div>

    <!-- 代码片段卡片列表 -->
    <div class="code-list">
      <a-spin :spinning="loading">
        <div class="card-grid">
          <div
            v-for="item in codeList"
            :key="item.id"
            class="code-card card-shadow neon-border"
            @click="goToDetail(item.id)"
          >
            <!-- 代码内容预览 -->
            <div class="code-preview">
              <MdPreview
                :modelValue="item.content"
                :theme="'dark'"
                :previewTheme="'github'"
                :codeTheme="'github'"
                :codeFoldable="false"
                :showCodeRowNumber="false"
                class="md-preview"
              />
            </div>

            <!-- 卡片底部信息 -->
            <div class="card-footer">
              <h3 class="code-title">{{ item.title }}</h3>
              <div class="code-meta">
                <div class="tags">
                  <a-tag v-for="tag in parseTags(item.tags)" :key="tag" color="blue">
                    {{ tag }}
                  </a-tag>
                </div>
                <div class="info">
                  <span class="view-count">👁️ {{ item.viewCount }}</span>
                  <span class="create-time">{{ formatTime(item.createTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <a-empty v-if="!loading && codeList.length === 0" description="暂无代码片段" />
      </a-spin>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <a-pagination
        v-model:current="pageNo"
        v-model:page-size="pageSize"
        :total="total"
        :show-size-changer="true"
        :show-total="(total) => `共 ${total} 条`"
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { pageCode } from '@/api/code'
import type { CodeVO } from '@/types/api'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()

const searchKeyword = ref('')
const loading = ref(false)
const codeList = ref<CodeVO[]>([])
const pageNo = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取代码列表
const fetchCodeList = async () => {
  loading.value = true
  try {
    const res = await pageCode({
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      title: searchKeyword.value || undefined,
    })
    codeList.value = res.data.list
    total.value = parseInt(res.data.total)
  } catch (error) {
    console.error('获取代码列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pageNo.value = 1
  fetchCodeList()
}

// 分页变化
const handlePageChange = () => {
  fetchCodeList()
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push({
    path: `/code/${id}`,
    query: { keyword: searchKeyword.value || undefined }
  })
}

// 解析标签
const parseTags = (tags?: string) => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return []
  }
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

onMounted(() => {
  // 从路由query中恢复搜索关键词
  const keyword = route.query.keyword as string
  if (keyword) {
    searchKeyword.value = keyword
  }
  fetchCodeList()
})
</script>

<style scoped>
.home-container {
  max-width: 1400px;
  margin: 0 auto;
}

.search-section {
  margin-bottom: 32px;
}

.search-box {
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  border-radius: 8px;
}

.code-list {
  min-height: 400px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.code-card {
  background: linear-gradient(135deg, #1a1f3a 0%, #0f1229 100%);
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 500px;
}

.code-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(74, 158, 255, 0.3);
}

.code-preview {
  flex: 1;
  overflow: hidden;
  position: relative;
  max-height: 350px;
  padding: 16px;
  background: #0a0e27;
}

.md-preview {
  max-height: 320px;
  overflow: hidden;
  position: relative;
}

.md-preview::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(to bottom, transparent, #0a0e27);
  pointer-events: none;
}

.card-footer {
  padding: 16px;
  border-top: 1px solid rgba(74, 158, 255, 0.2);
  background: rgba(26, 31, 58, 0.5);
}

.code-title {
  font-size: 18px;
  font-weight: bold;
  color: #4a9eff;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.code-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8a8fa8;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 深色主题的 Markdown 预览样式 */
:deep(.md-editor-preview) {
  background: transparent !important;
  color: #e0e0e0 !important;
}

:deep(.md-editor-preview-wrapper) {
  padding: 0 !important;
}

:deep(.md-editor-preview h1),
:deep(.md-editor-preview h2),
:deep(.md-editor-preview h3) {
  color: #4a9eff !important;
  border-bottom-color: #3d4466 !important;
}

:deep(.md-editor-preview code) {
  background: #1a1f3a !important;
  color: #4a9eff !important;
}

:deep(.md-editor-preview pre) {
  background: #1a1f3a !important;
  padding: 16px !important;
  overflow-x: auto !important;
}

:deep(.md-editor-preview pre code) {
  background: transparent !important;
  padding: 0 !important;
}

:deep(.md-editor-preview a) {
  color: #4a9eff !important;
}
</style>

